<?php

namespace Drupal\shushengyuan\Schemas;

use Drupal\shusy_category\Entity\ShusyCategory;
use Drupal\shusy_point_product\Entity\ShusyPointProduct;
use EntityListWrapper;

/**
 * @OA\Schema(
 *   schema="PointProductItem",
 *   type="object",
 *   description="PointProductItem"
 * )
 */
class PointProductItem extends AbstractBaseModel {

  protected function getEntityType() {
    return 'shusy_point_product';
  }

  protected function setValue() {
    if ($this->entity instanceof ShusyPointProduct) {
      $value = [
        /**
         * @OA\Property(
         *   property="id",
         *   type="integer",
         *   description="ID",
         * ),
         */
        'id' => (int) $this->entity->id,
        /**
         * @OA\Property(
         *   property="name",
         *   type="string",
         *   description="产品名",
         * ),
         */
        'name' => (string) $this->entity->name,
        /**
         * @OA\Property(
         *   property="point",
         *   type="integer",
         *   description="所需积分",
         * ),
         */
        'point' => (int) $this->entity->point,
        /**
         * @OA\Property(
         *   property="image",
         *   type="string",
         *   description="封面",
         * ),
         */
        'image' => (string) $this->getImage(),
        /**
         * @OA\Property(
         *   property="category",
         *   type="string",
         *   description="类别",
         * ),
         */
        'category' => $this->getCategory(),
        /**
         * @OA\Property(
         *   property="stock",
         *   type="integer",
         *   description="库存",
         * ),
         */
        'stock' => $this->entity->stock(),
      ];
      $this->merge($value);
    }
  }

  protected function getImage() {
    $field_image = $this->wrapper->field_image->value();
    if (empty($field_image)) {
      $field_images = $this->wrapper->field_images;
      if ($field_images instanceof EntityListWrapper) {
        foreach ($field_images as $image) {
          $field_image = $image->value();
          break;
        }
      }
    }
    return $this->imageStyleUrl('ProductItemImage', $field_image);
  }

  protected function getCategory() {
    $category = shusy_category_load($this->entity->category_id);
    if ($category instanceof ShusyCategory) {
      return $category->name;
    }
    return '';
  }
}
